//
//  CatogryGiftMainViewController.m
//  project
//
//  Created by lanou on 15/10/28.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "CatogryGiftMainViewController.h"
#import "CatogryGiftTableViewCell.h"
#import "CatogryGiftMainCollectionViewCell.h"
#import "PKRequestManager.h"
#import "CatogryMainCollectionModel.h"
#import "CatogryArtifactViewController.h"
#import "CatogryGiftDetailViewController.h"
#import "CatogryGifteReusableView.h"

@interface CatogryGiftMainViewController () <UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>

//创建一个tableView
@property(nonatomic,strong)UITableView *giftMainTableView;
//创建一个collectionView
@property(nonatomic,strong)UICollectionView *giftMainCollectionView;
//创建一个表头的imageView
@property(nonatomic,strong)UIButton *artifactImageView;

//创建一个装table数据的数组
@property(nonatomic,strong)NSMutableArray *tableDataArray;
//创建一个装collection数据的数组



@end

@implementation CatogryGiftMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    

    _artifactImageView = [UIButton buttonWithType:UIButtonTypeCustom];
    _artifactImageView.frame = CGRectMake(0, 70, kWidth, 40);
    _artifactImageView.backgroundColor = [UIColor whiteColor];
    //神器上面的定位图片
    UIImageView *locationImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 20, 20)];
    locationImageView.layer.masksToBounds = YES;
    locationImageView.layer.cornerRadius = 10;
    locationImageView.backgroundColor = [UIColor greenColor];
    locationImageView.image = [UIImage imageNamed:@"iconfont-dingweizhuanhuan"];
    [_artifactImageView addSubview:locationImageView];
    //文字
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(35, 10, 100, 20)];
    titleLabel.text = @"选礼神器";
    [_artifactImageView addSubview:titleLabel];
    //向右符
    UIImageView *rightImage = [[UIImageView alloc]initWithFrame:CGRectMake(kWidth - 40, 10, 20, 20)];
    rightImage.image = [UIImage imageNamed:@"iconfont-xiangyoujiantou"];
    [_artifactImageView addSubview:rightImage];
    
    //给选礼神器view添加轻拍手势
//    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(login:)];
//    [_artifactImageView addSubview:singleTap];
    [_artifactImageView addTarget:self action:@selector(login:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.view addSubview:_artifactImageView];
    
    _giftMainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 110, 70, kHeight - 110)];
    _giftMainTableView.backgroundColor = [[UIColor alloc]initWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    _giftMainTableView.showsVerticalScrollIndicator = NO;
    _giftMainTableView.dataSource = self;
    _giftMainTableView.delegate = self;
    [_giftMainTableView registerClass:[CatogryGiftTableViewCell class] forCellReuseIdentifier:@"CatogryGiftTableViewCell"];
    _tableDataArray = [NSMutableArray arrayWithCapacity:0];
    [self.view addSubview:_giftMainTableView];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake((kWidth - 130) / 3, (kWidth - 130) / 3 + 20);
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 10);
    layout.minimumInteritemSpacing = 20;
    layout.minimumLineSpacing = 20;
    layout.headerReferenceSize = CGSizeMake(kWidth - 80, 80);
    
    _giftMainCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(80, 110, kWidth - 70, kHeight - 170) collectionViewLayout:layout];
    _giftMainCollectionView.backgroundColor = [UIColor whiteColor];
    _giftMainCollectionView.dataSource = self;
    _giftMainCollectionView.delegate = self;
    [_giftMainCollectionView registerClass:[CatogryGiftMainCollectionViewCell class] forCellWithReuseIdentifier:@"CatogryGiftMainCollectionViewCell"];
    [_giftMainCollectionView registerClass:[CatogryGifteReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];
    [self.view addSubview:_giftMainCollectionView];
    
    [self requestData];
}

//选礼神器button的点击事件
-(void)login:(UIButton *)button
{
    CatogryArtifactViewController *artifactVC = [[CatogryArtifactViewController alloc]init];
    self.pushGiftItem(artifactVC);
}

//返回tableViewCell的分区个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableDataArray.count;
}

//配置tableViewCell的数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CatogryGiftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CatogryGiftTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = _tableDataArray[indexPath.row];
    return cell;
}

//返回collectionView的分区个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _tableDataArray.count;
}

//返回collectionViewCell的分区中item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return ((CatogryMainTableModel *)self.tableDataArray[section]).collectionArray.count;
}

//配置collectionViewCell的数据
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CatogryGiftMainCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CatogryGiftMainCollectionViewCell" forIndexPath:indexPath];
    cell.model = ((CatogryMainTableModel *)_tableDataArray[indexPath.section]).collectionArray[indexPath.row];
    return cell;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:@"UICollectionElementKindSectionHeader"])
    {
        CatogryGifteReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView" forIndexPath:indexPath];
        reusableView.titleLabel.text = ((CatogryMainTableModel *)_tableDataArray[indexPath.section]).name;
        return reusableView;
    }
    else {
        return nil;
    }
}

//推出点击item的界面
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CatogryGiftDetailViewController *giftDetailVC = [[CatogryGiftDetailViewController alloc]init];
    //调用bloc方法
    self.pushGiftItem(giftDetailVC);
    CatogryMainCollectionModel *model = ((CatogryMainTableModel *)_tableDataArray[indexPath.section]).collectionArray[indexPath.row];
    giftDetailVC.id = model.id;
    giftDetailVC.titleString = model.name;
}

//给tableView和collectionView请求数据
-(void)requestData
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    
    [PKRequestManager requestWithTypeP:GET urlString:@"http://api.liwushuo.com/v2/item_categories/tree" parDic:parDic finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSDictionary *dict = dic[@"data"];
        NSArray *arr = dict[@"categories"];
        for (NSDictionary *dicModel in arr)
        {
            CatogryMainTableModel *model = [[CatogryMainTableModel alloc]init];
            [model setValuesForKeysWithDictionary:dicModel];
            [_tableDataArray addObject:model];
        }
        [_giftMainTableView reloadData];
        [_giftMainCollectionView reloadData];
        
        
    } error:^(NSError *error) {
        NSLog(@"数据请求失败");
    }];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
dispatch_async(dispatch_get_main_queue(), ^{
           for (int i = 0; i < _tableDataArray.count; i++)
           {
               CatogryMainTableModel *model = _tableDataArray[i];
               model.isselect = NO;
               
               CatogryGiftTableViewCell *cell = [_giftMainTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
               cell.view.hidden = YES;
           }
           
           NSArray *array = [_giftMainCollectionView indexPathsForVisibleSupplementaryElementsOfKind:UICollectionElementKindSectionHeader];
           NSIndexPath *index = array[0];
           CatogryMainTableModel *model = _tableDataArray[index.section];
           model.isselect = YES;
           [_giftMainTableView reloadData];
           

       });
    
  
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    for (int i = 0; i < _tableDataArray.count; i++)
    {
        CatogryMainTableModel *model = _tableDataArray[i];
        model.isselect = NO;
        
        CatogryGiftTableViewCell *cell = [_giftMainTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        cell.view.hidden = YES;
        
    }
    NSIndexPath *index = [NSIndexPath indexPathForItem:0 inSection:indexPath.row];
    [_giftMainCollectionView scrollToItemAtIndexPath:index atScrollPosition: UICollectionViewScrollPositionTop animated:YES];
    CatogryGiftTableViewCell *cell = [_giftMainTableView cellForRowAtIndexPath:indexPath];
    cell.view.hidden = NO;
    CatogryMainTableModel *model = self.tableDataArray[indexPath.row];
    model.isselect = YES;

    
}


-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{

        CatogryGiftTableViewCell *cell = [_giftMainTableView cellForRowAtIndexPath:indexPath];
        cell.view.hidden = YES;
        
        CatogryMainTableModel *model =  self.tableDataArray[indexPath.row];
        model.isselect = NO;

   
    
}


//- (NSArray<NSIndexPath *> *)indexPathsForVisibleSupplementaryElementsOfKind:(NSString *)elementKind NS_AVAILABLE_IOS(9_0)
//{
//    
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
